//
//  HPRequestModel.m
//  Network
//
//  Created by phq on 2019/7/4.
//  Copyright © 2019 phq. All rights reserved.
//

#import "HPRequestModel.h"
#import "HPHelper.h"
#import "HPRequest.h"
#import "HPEncode.h"

static NSString const *prefix = @"http://product.yl1001.com/";
static NSString const *suffix = @"/open/index";
@implementation HPRequestModel

- (instancetype)init {
    self = [super init];
    if (self) {
        self.postParams = @"";
        self.getParams = @"";
    }
    return self;
}

+ (instancetype)initWithPath:(NSString *)path param:(NSDictionary *)param op:(NSString *)op func:(NSString *)func {
    HPRequestModel *model = [[HPRequestModel alloc] init];
    model.postParams = [model paramFormat:param];
    [model paramsConfigWithOp:op func:func path:path];
    return model;
}

#pragma mark - Public API

// post数据转换成服务器所需要的格式
- (NSString *)paramFormat:(NSDictionary *)param {
    if (param == nil || ![param isKindOfClass:[NSDictionary class]]) return @"";
    NSMutableString *str = [[NSMutableString alloc] init];
    for (NSString *key in param.allKeys) {
        if (str.length > 0) [str appendString:@"&"];
        [str appendString:key];
        [str appendString:@"="];
        NSString *encodString = [self jsonObject:[param objectForKey:key]];
        [str appendString:encodString];
    }
    return str;
}

// 2023中台微服务新体系
- (void)paramsConfigWithOp:(NSString *)op func:(NSString *)func path:(NSString *)path {
    HPInfo *info = [HPNetworking infoOnType:ATokenTypeJavas];
    info.url = [NSString stringWithFormat:@"%@/%@%@",info.urlPrefix,path,info.urlSuffix];
    [self paramsConfigWithOp:op func:func tokenType:ATokenTypeJavas addVersion:YES];
}

// 接口参数配置的抽象
- (void)paramsConfigWithOp:(NSString *)op func:(NSString *)func tokenType:(ATokenType)type {
    [self paramsConfigWithOp:op func:func tokenType:type addVersion:YES];
}

// 接口参数配置的抽象，可不带版本号
- (void)paramsConfigWithOp:(NSString *)op func:(NSString *)func tokenType:(ATokenType)type addVersion:(BOOL)addVer {
    self.type = type;
    HPInfo *info = [HPNetworking infoOnType:type];
    NSString *secret = info.secret;
    NSString *token = info.accessToken;

    self.dateGMT = [HPHelper stringFromDateGMT];
    
    if (type > 6) {
        NSString *path = [NSString stringWithFormat:@"/%@/%@/%@",info.ver,op,func];
        NSString *token = [self accessTokenWithSecret:info.accessToken params:_postParams urlPath:path dateGMT:_dateGMT];
        self.getParams = [NSString stringWithFormat:@"?op=%@&func=%@&secret=%@&access_token=%@&version=%@",op,func,info.secret,token,info.ver];
    }else {
        NSString *params = [NSString stringWithFormat:@"?gtype=http&secret=%@&access_token=%@&op=%@&func=%@",secret,token,op,func];
        self.getParams = addVer?[params stringByAppendingFormat:@"&version=%@",info.ver]:params;
    }
    
    if (![info.accessToken isKindOfClass:[NSString class]] || info.accessToken == nil || [info.accessToken length] == 0 || [info.accessToken containsString:@"null"] || [info.accessToken containsString:@"(null)"] ||
        ![info.secret isKindOfClass:[NSString class]] || info.secret == nil || [info.secret length] == 0 || [info.secret containsString:@"null"] || [info.secret containsString:@"(null)"]) {
        [info infoForcedUpdate:NO];
    }
}

#pragma mark - Private API

/*中文编码*/
- (NSString *)jsonObject:(id)value {
    if ([value isKindOfClass:[NSString class]]){
        return [HPHelper utf8Encode:value];
    }
    else if ([value isKindOfClass:[NSNumber class]]){
        return [NSString stringWithFormat:@"%@",value];
    }
    else if ([value isKindOfClass:[NSArray class]]){
        NSArray *arr = value;
        if (arr.count <= 0) {
            return @"";
        }
        NSMutableArray *newArr = [[NSMutableArray alloc] init];
        for (id obj in arr) {
            [newArr addObject:[self jsonObject:obj]];
        }
        return [HPHelper stringWithJson:newArr];
    }else if ([value isKindOfClass:[NSDictionary class]]){
        NSDictionary *dic = value;
        if (dic.count <= 0) {
            return @"";
        }
        
        NSMutableDictionary *newDic = [[NSMutableDictionary alloc] init];
        for (NSString *key in dic.allKeys){
            id obj = [dic objectForKey:key];
            [newDic setObject:[self jsonObject:obj] forKey:key];
        }
        return [HPHelper stringWithJson:newDic];
    }
    return value;
}

#pragma mark - online_training

// 使用 token_secret 完成签名，生成 access_token
- (NSString *)accessTokenWithSecret:(NSString *)secret
                             params:(NSString *)params
                            urlPath:(NSString *)urlPath
                            dateGMT:(NSString *)dateGMT {
    secret = secret?:@"";
    params = params?:@"";
    urlPath = urlPath?:@"";
    dateGMT = dateGMT?:@"";
    
    NSString *paramsMd5 = [params.stringByRemovingPercentEncoding md5Encode];
    NSString *paramsMd5Base64 = [paramsMd5 base64Encode];
    NSString *signInfo = [NSString stringWithFormat:@"%@\n%@\n%@",dateGMT,paramsMd5Base64,urlPath];
    NSString *hmacsha1Base64 = [signInfo hmacsha1EncodeWithKey:secret];;
    NSString *accessToken = [hmacsha1Base64 md5Encode];

#if 0  // debug
    NSLog(@"------ 原参数 -----");
    NSLog(@"------token_secret = %@",secret);
    NSLog(@"------parameters = %@",params);
    NSLog(@"------urlPath = %@",urlPath);
    NSLog(@"------dateGMT = %@",dateGMT);

    NSLog(@"------ 加密过程参数变化 -----");
    NSLog(@"------parameters (parameters + Md5) = %@",paramsMd5);
    NSLog(@"------parameters (parameters + base64) = %@",paramsMd5Base64);
    NSLog(@"------signInfo = %@",signInfo);
    NSLog(@"------hmacsha1 (signInfo + hmacsha1 + base64) = %@",hmacsha1Base64);
    NSLog(@"------accessToken (hmacsha1 + md5) = %@",accessToken);
#endif

    return accessToken;
}


@end
